package com.FH.applyFrom.vacationForm;

import com.FH.applyForm.officeServies.vacationtype.VacationTypeResource;
import com.FH.organization.operator_log.OperatorLogPullDTO;
import com.FH.organization.operator_log.OperatorLogResource;
import com.FH.organization.people.KamMemberResource;
import com.FH.organization.suggestion.SuggestionResource;
import com.FH.organization.work_flow.WorkFlowPullDTO;
import com.FH.organization.work_flow.WorkFlowResource;
import com.FH.util.AccessDB;
import com.FH.util.ResultDTO;
import com.FH.util.warnSrc;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import javax.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/7/14.
 * 休假申请单实现类
 */
@Stateless
public class VacationFormDAOImpl extends AccessDB implements VacationFormDAO {

    /**
     * 获取休假申请单信息
     *
     * @param search
     * @param page
     * @param size
     * @return
     */

    @Inject
    OperatorLogResource operatorLogResource;

    @Inject
    WorkFlowResource workFlowResource;

    @Inject
    VacationFormResource vacationFormResource;

    @Inject
    VacationTypeResource vacationTypeResource;
    @Inject
    KamMemberResource kamMemberResource;
    @Inject
    SuggestionResource suggestionResource;

    @Override
    public ResultDTO getVacationFormInfo(String search, String page, String size) {

        ResultDTO resultDTO = new ResultDTO();

        try {

            JSONObject jsonObject = new JSONObject(search);

            String sql_w = "";//查询条件sql组合

            String sql_page = "";//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(size);
            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok) + "," + size + "";
            }

            if (jsonObject.has("isverify")) {
                sql_w += " AND isverify ='" + jsonObject.getString("isverify") + "'";
            }
//            else {
//                sql_w += " AND (isverify IS NULL OR isverify=0)";
//            }
            
            if (jsonObject.has("member_id")) { //用户id
                sql_w += " AND member_id ='" + jsonObject.getString("member_id") + "'";
            }

            if (jsonObject.has("vacation_form_id")) { //休假申请单主键id
                sql_w += " AND vacation_form_id ='" + jsonObject.getString("vacation_form_id") + "'";

            }

            String sqlexit = "select count(1) from vacation_form  where 1=1 ";
            String sqlexit_ok = sqlexit + sql_w;

            String existName = getReportingToOne(sqlexit_ok);//查询此数据是否存在

            List<String[]> seresult = new ArrayList<String[]>();

            List<VacationFormShowDTO> result = new ArrayList<VacationFormShowDTO>();

            if (!existName.equals("0")) {
                String sql = "SELECT vacation_form_id,vacation_createtime,vacation_updatetime,vacationresion,vacation_form_starttime,vacation_form_endtime,member_id,vacation_form_disdays,vacationtypename,fail_resource" +
                        " FROM vacation_form WHERE 1=1" + sql_w + " ORDER BY vacation_createtime DESC" + sql_page;

                seresult = this.getReportingTo(sql);
            }

            if (seresult.size() > 0) {
                //如果查询成功，构建返回对象
                for (int i = 0; i < seresult.size(); i++) {
                    VacationFormShowDTO vacationFormShowDTO = new VacationFormShowDTO();
                    vacationFormShowDTO.setVacation_form_id(seresult.get(i)[1]);
                    vacationFormShowDTO.setVacation_createtime(seresult.get(i)[2]);
                    vacationFormShowDTO.setVacation_updatetime(seresult.get(i)[3]);
                    vacationFormShowDTO.setVacationresion(seresult.get(i)[4]);
                    vacationFormShowDTO.setVacation_form_starttime(seresult.get(i)[5]);
                    vacationFormShowDTO.setVacation_form_endtime(seresult.get(i)[6]);
                    vacationFormShowDTO.setMember_id(seresult.get(i)[7]);
                    vacationFormShowDTO.setVacation_form_disdays(seresult.get(i)[8]);
                    vacationFormShowDTO.setVacationtypename(seresult.get(i)[9]);
                    vacationFormShowDTO.setFail_resource(seresult.get(i)[10]);
                    ResultDTO worklist = null, vacationtypes = null, kamMenber = null,suggestion=null;

                    if (jsonObject.has("isverify")) {
                        String state = jsonObject.getString("isverify");
                        worklist = workFlowResource.getWorkFlowInfo("{work_flow_formid:" + seresult.get(i)[1] + ",work_flow_state:" + state + "}", "1", "20");
                    } else {
                        worklist = workFlowResource.getWorkFlowInfo("{work_flow_formid:" + seresult.get(i)[1] + "}", "1", "20");
                    }

                    vacationFormShowDTO.setWs(worklist.getValues());

                    vacationtypes = vacationTypeResource.getVacationTypeInfo("{vacationtypename:" + seresult.get(i)[9] + "}", "1", "20");
                    vacationFormShowDTO.setVacatypes(vacationtypes.getValues());

                    kamMenber=kamMemberResource.getUserListInfo("{member_id:" + seresult.get(i)[7] + "}", "1", "1");
                    vacationFormShowDTO.setKamMemberShowDTOList(kamMenber.getValues());

                    if(seresult.get(i)[1] != null && ! seresult.get(i)[1].equals("")){

                        suggestion=suggestionResource.getSuggestionInfo("{form_id:" + seresult.get(i)[1] + "}", "1", "100");
                        vacationFormShowDTO.setSuggestionShowDTOs(suggestion.getValues());
                    }
                    result.add(vacationFormShowDTO);
                }

                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }
            resultDTO.setStr(result.size() + "");
            resultDTO.setValues(result);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultDTO;
    }

    /**
     * 增加休假申请单信息
     *
     * @param vacationFormPullDTO
     * @return
     */
    @Override
    public ResultDTO addVacationFormInfo(VacationFormPullDTO vacationFormPullDTO) {


        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());


        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        int resultls = 0;


        String existName = "";
        /**
         * 判断是否已存在
         *
         * 若存在 执行update方法
         *
         * 若不存在  执行add方法
         */

        if (vacationFormPullDTO.getVacation_form_id() != null && !vacationFormPullDTO.getVacation_form_id().equals("")) {

            String sql = "select count(1) from vacation_form where vacation_form_id='" + vacationFormPullDTO.getVacation_form_id() + "'";

            existName = getReportingToOne(sql);

            if (!existName.equals("0")) {
                return vacationFormResource.updateVacationFormInfo(vacationFormPullDTO);
            }
        }
        /**
         * 判断是否年假
         */
//        String vacation_form_disdays = "";
//        if(vacationFormPullDTO.getVacationtypename()!=null&&!"".equals(vacationFormPullDTO.getVacationtypename())&&vacationFormPullDTO.getVacationtypename().equals("2")){
//
//            vacation_form_disdays = vacationFormPullDTO.getVacation_form_disdays();
//        }

        //构建返回对象
        ResultDTO resultDTO = new ResultDTO();

        String organization_insert = "";
        //构建插入sql
        organization_insert += "INSERT  INTO vacation_form(vacation_form_id,vacationresion,vacation_form_starttime,vacation_form_endtime,member_id,fail_resource,vacation_form_disdays,vacation_createtime,vacation_updatetime,vacationtypename,isverify)" +
                "VALUES('" + uuid + "','" + vacationFormPullDTO.getVacationresion() + "','" + vacationFormPullDTO.getVacation_form_starttime() + "','" +
                vacationFormPullDTO.getVacation_form_endtime() + "','" + vacationFormPullDTO.getMember_id() + "','" + " " + "','" + vacationFormPullDTO.getVacation_form_disdays() + "','" + time + "','" + " " + "','" + vacationFormPullDTO.getVacationtypename() + "','0')";

        //插入业务表
        resultls = addReportingTo(organization_insert);

        if (resultls != 0) {

            resultDTO.setStr(uuid);
            // resultDTO.setStr(vacationFormPullDTO.getVacationtypename());
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
            //日志操作
            OperatorLogPullDTO operatorlogPullDTO = new OperatorLogPullDTO();
            operatorlogPullDTO.setWork_form_id(uuid);
            operatorlogPullDTO.setOperator_log_type("休假申请");
            operatorlogPullDTO.setOperator_log_title(vacationFormPullDTO.getVacationresion());
            operatorlogPullDTO.setOperator_log_content("请假时间  "+vacationFormPullDTO.getVacation_form_starttime()+"至"+vacationFormPullDTO.getVacation_form_endtime());
            operatorlogPullDTO.setMember_id(vacationFormPullDTO.getMember_id());
            operatorLogResource.addOperatorLogInfo(operatorlogPullDTO);
            //流程上报
            WorkFlowPullDTO workFlowPullDTO = new WorkFlowPullDTO();
            workFlowPullDTO.setWork_flow_formid(uuid);
            workFlowPullDTO.setWork_flow_type("vacation_form");
            workFlowPullDTO.setWork_flow_desc("休假申请单请求审批");
            workFlowPullDTO.setWork_flow_date(time);
            workFlowPullDTO.setWork_flow_order("0");
            workFlowPullDTO.setWork_flow_createid(vacationFormPullDTO.getMember_id());
            workFlowPullDTO.setWork_flow_approval(vacationFormPullDTO.getReport_people());
            workFlowPullDTO.setWork_flow_approval_organization_id(vacationFormPullDTO.getWork_flow_approval_organization_id());
            workFlowPullDTO.setFlow_path_id(vacationFormPullDTO.getFlow_path_id());
            workFlowPullDTO.setWork_flow_suggestion("");
            workFlowResource.addWorkFlowInfo(workFlowPullDTO);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }
        return resultDTO;

    }

    /**
     * 修改方法
     *
     * @param vacationFormPullDTO
     * @return
     */
    @Override
    public ResultDTO updateVacationFormInfo(VacationFormPullDTO vacationFormPullDTO) {

        ResultDTO resultDTO = new ResultDTO();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        String QUERY = "";

        //    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //更新sql语句
        QUERY += "update vacation_form set vacation_updatetime ='" + time + "'";

        if (null != vacationFormPullDTO.getIsverify() && !"".equals(vacationFormPullDTO.getIsverify())) {
            QUERY += ",isverify ='" + vacationFormPullDTO.getIsverify() + "'";
        }

        if (null != vacationFormPullDTO.getVacationresion() && !"".equals(vacationFormPullDTO.getVacationresion())) {
            QUERY += ",vacationresion ='" + vacationFormPullDTO.getVacationresion() + "'";
        }
        if (null != vacationFormPullDTO.getVacation_form_starttime() && !"".equals(vacationFormPullDTO.getVacation_form_starttime())) {
            QUERY += ",vacation_form_starttime ='" + vacationFormPullDTO.getVacation_form_starttime() + "'";
        }

        if (null != vacationFormPullDTO.getVacation_form_endtime() && !"".equals(vacationFormPullDTO.getVacation_form_endtime())) {
            QUERY += ",vacation_form_endtime ='" + vacationFormPullDTO.getVacation_form_endtime() + "'";
        }
        if (null != vacationFormPullDTO.getMember_id() && !"".equals(vacationFormPullDTO.getMember_id())) {
            QUERY += ",member_id ='" + vacationFormPullDTO.getMember_id() + "'";
        }

        if (null != vacationFormPullDTO.getVacation_type() && !"".equals(vacationFormPullDTO.getVacation_type())) {
            QUERY += ",vacation_type ='" + vacationFormPullDTO.getVacation_type() + "'";
        }
        if (null != vacationFormPullDTO.getFail_resource() && !"".equals(vacationFormPullDTO.getFail_resource())) {
            QUERY += ",fail_resource ='" + vacationFormPullDTO.getFail_resource() + "'";
        }

        if (null != vacationFormPullDTO.getVacation_form_disdays() && !"".equals(vacationFormPullDTO.getVacation_form_disdays())) {
            QUERY += ",vacation_form_disdays ='" + vacationFormPullDTO.getVacation_form_disdays() + "'";
        }
        if (null != vacationFormPullDTO.getVacation_createtime() && !"".equals(vacationFormPullDTO.getVacation_createtime())) {
            QUERY += ",vacation_createtime ='" + vacationFormPullDTO.getVacation_createtime() + "'";
        }

        QUERY += " where vacation_form_id = '" + vacationFormPullDTO.getVacation_form_id() + "'";

        int result = this.addReportingTo(QUERY);

        // 判断SQl是否执行成功
        if (result != 0) {
            WorkFlowPullDTO workFlowPullDTO = new WorkFlowPullDTO();
            workFlowPullDTO.setWork_flow_formid(vacationFormPullDTO.getVacation_form_id());
            workFlowPullDTO.setWork_flow_approval(vacationFormPullDTO.getReport_people());
            workFlowPullDTO.setWork_flow_approval_organization_id(vacationFormPullDTO.getWork_flow_approval_organization_id());
            workFlowPullDTO.setWork_flow_order("0");
            workFlowPullDTO.setIsverify("0");
            workFlowResource.updateWorkFlowInfo(workFlowPullDTO);
            resultDTO.setStr(vacationFormPullDTO.getVacation_form_id());
            resultDTO.setStatus("90000");//
            resultDTO.setDescritpion(warnSrc.update_success);
        } else {
            resultDTO.setStatus("90001");//
            resultDTO.setDescritpion(warnSrc.update_fail);
        }
        return resultDTO;
    }


    /**
     * 删除方法
     *
     * @param vacationFormPullDTO
     * @return
     */
    @Override
    public ResultDTO deleteVacationFormInfo(VacationFormPullDTO vacationFormPullDTO) {

        //删除之前查询一遍该表是否有记录
        String sql = "select count(1) from vacation_form where vacation_form_id='" + vacationFormPullDTO.getVacation_form_id() + "'";

        String existName = getReportingToOne(sql);

        int result = 0;

        ResultDTO resultDTO = new ResultDTO();

        if (!existName.equals("0")) {
            String QUERY = "";
            QUERY += "delete from vacation_form where vacation_form_id='" + vacationFormPullDTO.getVacation_form_id() + "'";

            result = this.addReportingTo(QUERY);
        }
        if (result != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);

            WorkFlowPullDTO workFlowPullDTO = new WorkFlowPullDTO();
            workFlowPullDTO.setWork_flow_formid(vacationFormPullDTO.getVacation_form_id());
            workFlowResource.deleteWorkFlowInfo(workFlowPullDTO);

        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }
}
